import { defineStore } from 'pinia'
import router from '@/router'
import { sStorage } from '@/utils/cache'

export const activeTab = sStorage.get('activeTab')
export const tabs = sStorage.get('tabs')

const WITHOUT_TAB_PATHS = ['/404', '/login', '/forbidden']

export const useTabsStore = defineStore('tab', {
    state() {
        return {
            tabs: tabs || [],
            activeTab: activeTab || '',
        }
    },
    getters: {
        activeIndex() {
            return this.tabs.findIndex((item) => item.path === this.activeTab)
        },
    },
    actions: {
        setActiveTab(path) {
            this.activeTab = path
            sStorage.set('activeTab', path)
        },
        setTabs(tabs) {
            this.tabs = tabs
            sStorage.set('tabs', tabs)
        },
        addTab(tab = {}) {
            this.setActiveTab(tab.path)
            if (WITHOUT_TAB_PATHS.includes(tab.path) || this.tabs.some((item) => item.path === tab.path)) return
            this.setTabs([...this.tabs, tab])
        },
        removeTab(path) {
            if (path === this.activeTab) {
                if (this.activeIndex > 0) {
                    router.push(this.tabs[this.activeIndex - 1].path)
                } else {
                    router.push(this.tabs[this.activeIndex + 1].path)
                }
            }
            this.setTabs(this.tabs.filter((tab) => tab.path !== path))
        },
        removeOther(curPath = this.activeTab) {
            this.setTabs(this.tabs.filter((tab) => tab.path === curPath))
            if (curPath !== this.activeTab) {
                router.push(this.tabs[this.tabs.length - 1].path)
            }
        },
        removeLeft(curPath) {
            const curIndex = this.tabs.findIndex((item) => item.path === curPath)
            const filterTabs = this.tabs.filter((item, index) => index >= curIndex)
            this.setTabs(filterTabs)
            if (!filterTabs.find((item) => item.path === this.activeTab)) {
                router.push(filterTabs[filterTabs.length - 1].path)
            }
        },
        removeRight(curPath) {
            const curIndex = this.tabs.findIndex((item) => item.path === curPath)
            const filterTabs = this.tabs.filter((item, index) => index <= curIndex)
            this.setTabs(filterTabs)
            if (!filterTabs.find((item) => item.path === this.activeTab)) {
                router.push(filterTabs[filterTabs.length - 1].path)
            }
        },
        resetTabs() {
            this.setTabs([])
            this.setActiveTab('')
        },
    },
})